import yaml
from pathlib import Path


# 加载 YAML 配置
def load_bot_config():
    yaml_path = Path(__file__).parent / "npc_dsl.yaml"
    with open(yaml_path, encoding="utf-8") as f:
        return yaml.safe_load(f)


# 全局配置和状态机
config = load_bot_config()
states = config.get("states", {})
end_states = set(config.get("end_state", []))
start_state = config.get("start_state", "greet")

current_sessions = {}  # 用于存储每个用户的当前状态（简单版，生产环境建议用Redis）

def get_session_state(session_id):
    return current_sessions.get(session_id, start_state)

def set_session_state(session_id, state):
    current_sessions[session_id] = state

def handle_message(session_id, user_input):
    state = get_session_state(session_id)
    state_info = states.get(state)

    if not state_info:
        return {
            "output": "抱歉，系统出现了问题，请刷新重试。",
            "options": {},
            "next_state": "default_end"
        }

    if state in end_states:
        return {
            "output": state_info.get("output", "对话已结束。"),
            "options": {},
            "next_state": state
        }

    output_text = state_info.get("output", "暂无回复。")
    options = state_info.get("options", {})

    # 判断是否是结束状态（通过 options 是否为空 or 状态是否在 end_states）
    if not options:
        next_state = "default_end"
    else:
        next_state = None

    # 如果用户输入匹配某个选项
    if user_input in options:
        next_state = options[user_input]

    if next_state is None:
        # 未匹配选项，保持当前状态，提示重新输入（或可以返回错误信息）
        return {
            "output": output_text,
            "options": options,
            "next_state": state  # 停留在当前状态
        }

    # 更新状态
    set_session_state(session_id, next_state)

    # 处理新状态
    new_state_info = states.get(next_state, {})
    new_output = new_state_info.get("output", "没有更多信息了。")
    new_options = new_state_info.get("options", {})

    is_ending = next_state in end_states or not new_options

    return {
        "output": new_output,
        "options": new_options,
        "next_state": next_state,
        "is_ending": is_ending
    }